package com.easy.service.impl;

import com.easy.bean.User;
import com.easy.mapper.UserDao;
import com.easy.service.LoginService;
import com.easy.util.PasswordUtil;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserDao userDao;

    public User logininfo(String token) {
        // 获取token中的用户id
        Object id = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        if (id==null){
            throw new RuntimeException("登录异常");
        }
        User user=userDao.one(Integer.parseInt(id.toString()));
        return user;
    }

    @Override
    public String login(User user) {
        //登录逻辑
        //1.通过用户名查询数据库
        User result=userDao.getByAccount(user.getUser_account());
        if(result==null){
            throw new RuntimeException("登录异常");
        }
        //2.判断密码
        String password=user.getUser_password();
        String encryptionPassword=result.getUser_password();
        if(!PasswordUtil.checkPassword(password,encryptionPassword)){
            throw new RuntimeException("登录异常");
        }
        //3.返回结果token
        String token= TokenUtil.getToken(result.getId(),1);
        return token;
    }

    @Override
    public boolean changePassword(int id, String oldPassword, String newPassword) {
        // 1. 根据ID获取管理员信息
        User user = userDao.one(id);
        if (user == null) {
            throw new RuntimeException("管理员不存在");
        }

        // 2. 验证旧密码是否正确
        String encryptionPassword = user.getUser_password();
        if (!PasswordUtil.checkPassword(oldPassword, encryptionPassword)) {
            throw new RuntimeException("旧密码错误");
        }

        // 3. 加密新密码
        String newEncryptionPassword = PasswordUtil.getEncryption(newPassword);

        // 4. 更新密码
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setUser_password(newEncryptionPassword);

        int count = userDao.edit(updateUser);
        return count > 0;
    }
}
